package com.libre.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.libre.auth.entity.Role;
import com.libre.auth.entity.User;
import com.libre.auth.entity.UserRole;
import com.libre.auth.mapper.UserMapper;
import com.libre.auth.service.RoleService;
import com.libre.auth.service.UserRoleService;
import com.libre.auth.service.UserService;
import com.libre.common.enums.ResultEnum;
import com.libre.common.exception.BusinessRuntimeException;
import com.libre.common.utils.MD5Util;
import com.libre.common.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    UserMapper mapper;
    @Autowired
    RoleService roleService;
    @Autowired
    UserRoleService userRoleService;

    @Override
    public IPage<User> findPage(Page page, User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtil.isNotEmpty(user.getUsername())) queryWrapper.like("username", user.getUsername());
        if (StringUtil.isNotEmpty(user.getRealName())) queryWrapper.like("real_name", user.getRealName());
        queryWrapper.orderByDesc("created_time");
        queryWrapper.eq("is_delete", "0");
        Page<User> pages = this.page(page, queryWrapper);
        List<User> records = pages.getRecords();
        List<String> ids = records.stream().map(u -> u.getId()).collect(Collectors.toList());
        QueryWrapper<UserRole> userRoleQuery = new QueryWrapper<>();
        userRoleQuery.in("user_id", ids);
        userRoleQuery.eq("is_delete", "0");
        List<UserRole> list = userRoleService.list(userRoleQuery);
        records.forEach(u -> {
            List<UserRole> urList = list.stream().filter(it -> u.getId().equals(it.getUserId())).collect(Collectors.toList());
            List<Role> roles = Lists.newArrayList();
            urList.forEach(ur -> {
                Role role = new Role();
                role.setId(ur.getRoleId());
                roles.add(role);
            });
            u.setRoles(roles);
        });
        return pages;
    }

    @Override
    public List<User> findList(User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtil.isNotEmpty(user.getUsername())) queryWrapper.like("username", user.getUsername());
        if (StringUtil.isNotEmpty(user.getRealName())) queryWrapper.like("real_name", user.getRealName());
        queryWrapper.orderByDesc("created_time");
        queryWrapper.eq("is_delete", "0");
        List<User> list = mapper.selectList(queryWrapper);
        return list;
    }

    @Override
    public boolean addOrUpdate(User user) {
        //判断用户名是否已存在
        QueryWrapper<User> nameQuery = new QueryWrapper<>();
        nameQuery.eq("username", user.getUsername());
        if (StringUtil.isNotEmpty(user.getId())) nameQuery.ne("id", user.getId());
        List<User> list = this.list(nameQuery);
        if (list.size() > 0) {
            //用户名已存在
            throw new BusinessRuntimeException(ResultEnum.USER_NAME_ALREADY_EXISTS.getReasonPhraseCN());
        }
        //判断用户编号是否已存在
        QueryWrapper<User> codeQuery = new QueryWrapper<>();
        codeQuery.eq("code", user.getCode());
        if (StringUtil.isNotEmpty(user.getId())) codeQuery.ne("id", user.getId());
        List<User> list1 = this.list(codeQuery);
        if (list1.size() > 0) {
            //用户编号已存在
            throw new BusinessRuntimeException(ResultEnum.USER_CODE_ALREADY_EXISTS.getReasonPhraseCN());
        }
        //用户盐
        String satl = StringUtil.randomString(10);
        user.setSalt(satl);
        //密码加密
        user.setPassword(MD5Util.MD5(user.getPassword() + satl));
        //当头像为空时，添加默认用户头像
//        if(!StringUtil.isNotEmpty(user.getAvatar())){
//            user.setAvatar("default/nan.jpg");
//        }
        this.saveOrUpdate(user);
        //保存角色
        List<Role> roles = user.getRoles();
        List<UserRole> urs = new ArrayList<>();
        if (roles != null) {
            for (int i = 0; i < roles.size(); i++) {
                UserRole userRole = new UserRole();
                userRole.setRoleId(roles.get(i).getId());
                userRole.setUserId(user.getId());
                urs.add(userRole);
            }
            userRoleService.saveBatch(urs);
        }
        return true;
    }


//    @Override
//    public boolean edit(User user) {
//        //判断用户名是否已存在
//        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("username", user.getUsername());
//        List<User> list = this.list(queryWrapper);
//        if (list.size() > 0) {
//            //用户名已存在
//            throw new BusinessRuntimeException(ResultEnum.USER_NAME_ALREADY_EXISTS.getReasonPhraseCN());
//        }
//        //判断用户编号是否已存在
//        QueryWrapper<User> query = new QueryWrapper<>();
//        query.eq("user_code", user.getUserCode());
//        List<User> list1 = this.list(query);
//        if (list1.size() > 0) {
//            //用户编号已存在
//            throw new BusinessRuntimeException(ResultEnum.USER_CODE_ALREADY_EXISTS.getReasonPhraseCN());
//        }
//        //用户盐
//        String satl = StringUtil.randomString(10);
//        user.setSalt(satl);
//        //密码加密
//        user.setPassword(MD5Util.MD5(user.getPassword() + satl));
//        //当头像为空时，添加默认用户头像
////        if(!StringUtil.isNotEmpty(user.getAvatar())){
////            user.setAvatar("default/nan.jpg");
////        }
//        this.saveOrUpdate(user);
//        //保存角色
//        List<Role> roles = user.getRoles();
//        List<UserRole> urList = new ArrayList<>();
//        if(roles != null){
//            for (int i = 0; i < roles.size(); i++) {
//                UserRole userRole = new UserRole();
//                userRole.setRole_id(roles.get(i).getId());
//                userRole.setUser_id(user.getId());
//                urList.add(userRole);
//            }
//            userRoleService.saveBatch(urList);
//        }
//        return true;
//    }
}
